/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package LvodServer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.StringTokenizer;

/**
 *
 * @author wcss
 */
public class SingleHTTPServer extends Thread {

    public static String resultText = "error";
    private byte[] content;
    private byte[] header;
    private int port = 80;
    private String fileName = "";
    private String sourceName = "";
    private JReportQvodUrl report = null;
    private String encoding = "";
    private String mimeType = "";

    private SingleHTTPServer(String data, String encoding,
            String MIMEType, int port, JReportQvodUrl vod) throws UnsupportedEncodingException {
        this(data.getBytes(encoding), encoding, MIMEType, port, vod);
    }

    public SingleHTTPServer(byte[] data, String encodin, String MIMETyp, int port, JReportQvodUrl qvod) throws UnsupportedEncodingException {
        this.port = port;
        this.report = qvod;
        this.encoding = encodin;
        this.mimeType = MIMETyp;
    }

    public void makeHeaderData() throws UnsupportedEncodingException
    {
        this.content = SingleHTTPServer.resultText.getBytes(this.encoding);
        String header = "HTTP/1.0 200 OK\r\n"
                + "Server: OneFile 1.0\r\n"
                + "Content-length: " + this.content.length + "\r\n"
                + "Content-type: " + this.mimeType + "\r\n\r\n";
        this.header = header.getBytes("ASCII");

    }
    
    public void run() {
        try {
            ServerSocket server = new ServerSocket(this.port);
            System.out.println("Accepting connections on port " + server.getLocalPort());
            System.out.println("Data to be sent:");
            System.out.print(this.content + "\n");

            while (true) {
                Socket connection = null;
                try {
                    connection = server.accept();
                    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
                    InputStream in = new BufferedInputStream(connection.getInputStream());

                    StringBuffer request = new StringBuffer();
                    while (true) {
                        int c = in.read();
                        if (c == '\r' || c == '\n' || c == -1) {
                            break;
                        }
                        request.append((char) c);

                    }

                    String get = request.toString();
                    //记录日志  
                    //System.out.print(get + "\n");

                    if (get.toLowerCase().trim().startsWith("post")) 
                    {
                        String[] team = get.split(" ");
                        fileName = team[1];
                        sourceName = fileName.replace("/?data=", "");
                            if (!sourceName.toLowerCase().trim().startsWith("qvod://")) {
                                sourceName = "qvod://" + sourceName;
                            }
                            if (!sourceName.endsWith("|")) {
                                sourceName += "|";
                            }
                            if (this.report != null) {
                                this.report.reportQvodUrl(this, sourceName);
                            }
                            //System.out.println(sourceName + "\n");
                    }

                    makeHeaderData();
                    //如果检测到是HTTP/1.0及以后的协议，按照规范，需要发送一个MIME首部  
                    if (request.toString().indexOf("HTTP/") != -1) {
                        out.write(this.header);
                    }

                    out.write(this.content);
                    out.flush();

                } catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.close();
                    }
                }
            }

        } catch (IOException e) {
            System.err.println("Could not start server. Port Occupied");
        }
    }

    private static Thread qvodListen = null;
    
    private static void ssssssmain(String[] args) {
        try {
            String contentType = "text/plain";
            String data = "reportok";
            int port = 62351;
            String encoding = "utf-8";
            ReportQvodTest tt = new ReportQvodTest();
            Thread t = new SingleHTTPServer(data, encoding, contentType, port, tt);
            t.setDaemon(true);
            t.start();

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Usage:java SingleFileHTTPServer filename port encoding");
        } catch (Exception e) {
            System.err.println(e);// TODO: handle exception  
        }
    }

    public static final int listenPort = 62351;
    
    public static void startListen(JReportQvodUrl platform) {
        try {
            String contentType = "text/plain";
            String data = "reportok";
            String encoding = "utf-8";            
            qvodListen = new SingleHTTPServer(data, encoding, contentType, listenPort, platform);
            qvodListen.setDaemon(true);
            qvodListen.start();

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Usage:java SingleFileHTTPServer filename port encoding");
        } catch (Exception e) {
            System.err.println(e);// TODO: handle exception  
        }
    }
    
    public static void stopListen()
    {
        qvodListen.destroy();
    }
}
